package com.yisu.expressway.onedollar.fragment;

import static android.app.Activity.RESULT_OK;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.activity.GoodsPurchaseActivity;
import com.yisu.expressway.onedollar.activity.OrderDetailActivity;
import com.yisu.expressway.onedollar.activity.OrderExpressActivity;
import com.yisu.expressway.onedollar.activity.OrderShowBuildActivity;
import com.yisu.expressway.onedollar.activity.UserAddressActivity;
import com.yisu.expressway.onedollar.activity.UserAddressBuildActivity;
import com.yisu.expressway.onedollar.model.MyOrderItem;
import com.yisu.expressway.onedollar.model.UserAddressItem;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;
import com.yisu.expressway.utils.ToastUtil;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Kaven on 2016/12/19.
 */

public abstract class BaseMyOrderFragment extends BasicFragment
        implements PagingRecyclerView.SampleActionListener {
    public static final String TAG_ACTION_NET_ERR = "tag_action_net_err";
    public static final String TAG_ACTION_NORMAL = "tag_action_normal";
    @Bind(R.id.refreshLayout)
    protected SuperSwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.rv_content)
    protected PagingRecyclerView mRecyclerView;
    @Bind(R.id.empty)
    protected View emptyView;
    @Bind(R.id.empty_des)
    protected TextView mEmptyDesTv;
    @Bind(R.id.empty_action)
    protected TextView mEmptyActionTv;
    @Bind(R.id.empty_iv)
    protected ImageView mEmptyIv;
    protected ImageView carImage;
    protected AnimationDrawable mAnimation;
    private boolean isFreshEnable;
    private List<UserAddressItem> mUserAddressItems;

    @OnClick(R.id.empty_action)
    public void onClick(View view) {
        onActionClick(view);
    }

    protected abstract void onActionClick(View view);

    @Override
    protected int getInflateLayoutId() {
        return R.layout.fragment_all_order;
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    protected void releasePresenter() {

    }

    @Override
    protected void getIntentData(Intent intent) {

    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews(View view) {
        initFreshLayout();
        DividerListItemDecoration mListDivider = new DividerListItemDecoration(getContext(),
                LinearLayoutManager.VERTICAL);
        mRecyclerView.init(mListDivider, new LinearLayoutManager(getContext()), this, 20);
        getAddressList();
    }

    private void getAddressList() {
        ApiClientHelper.postApi(ApiSetting.getUserAddressList(),
                new TypeToken<List<UserAddressItem>>() {
                }, "", new Response.Listener<ApiResult<List<UserAddressItem>>>() {
                    @Override
                    public void onResponse(ApiResult<List<UserAddressItem>> result) {
                        if (!result.success) {
                            return;
                        }
                        List<UserAddressItem> result1 = result.getResult();
                        if (result1 != null) {
                            mUserAddressItems = result.getResult();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                    }
                }, this);
    }

    @Override
    protected void bindEvents() {

    }

    private View createHeaderView() {
        View headerView = getActivity().getLayoutInflater().inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    private void initFreshLayout() {
        mRefreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        mRefreshLayout.setHeaderView(createHeaderView());
        mRefreshLayout.setTargetScrollWithLayout(true);
        mRefreshLayout
                .setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

                    @Override
                    public void onRefresh() {
                        if (mAnimation != null) {
                            mAnimation.start();
                        }

                        mRecyclerView.refreshData();
                    }

                    @Override
                    public void onPullDistance(int distance) {
                        int index = distance / 25;

                        int resId = R.drawable.car_1;
                        switch (index) {
                            case 2:
                                resId = R.drawable.car_2;
                                break;
                            case 3:
                                resId = R.drawable.car_3;
                                break;
                            case 4:
                                resId = R.drawable.car_4;
                                break;
                            case 5:
                                resId = R.drawable.car_5;
                                break;
                            case 6:
                                resId = R.drawable.car_6;
                                break;
                            case 7:
                                resId = R.drawable.car_7;
                                break;
                            case 8:
                                resId = R.drawable.car_8;
                                break;
                            case 9:
                                resId = R.drawable.car_9;
                                break;
                            case 10:
                                resId = R.drawable.car_10;
                                break;
                        }
                        if (!isFreshEnable) {
                            carImage.setBackgroundResource(resId);
                        }

                    }

                    @Override
                    public void onPullEnable(boolean enable) {
                        isFreshEnable = enable;
                        if (enable) {
                            carImage.setBackgroundResource(R.color.colorTransparent);
                            carImage.setImageResource(R.drawable.car_frame);
                            mAnimation = (AnimationDrawable) carImage.getDrawable();
                        }
                    }
                });

    }


    @Override
    public void fetchData(int start, int pageSize) {
        fetchDataFromServer(start,pageSize);
    }

    protected void showEmptyView(boolean showEmpty, boolean netError) {
        emptyView.setVisibility(showEmpty ? View.VISIBLE : View.GONE);
        mRefreshLayout.setVisibility(showEmpty ? View.GONE : View.VISIBLE);
        if (showEmpty) {
            if (netError) {
                mEmptyActionTv.setText(getNetErrorAction());
                mEmptyActionTv.setTag(TAG_ACTION_NET_ERR);
                mEmptyDesTv.setText(getNetErrorDes());
                mEmptyIv.setImageDrawable(getNetErrorDrawable());
            } else {
                mEmptyActionTv.setTag(TAG_ACTION_NORMAL);
                mEmptyActionTv.setText(getEmptyAction());
                mEmptyDesTv.setText(getEmptyDes());
                mEmptyIv.setImageDrawable(getEmptyDrawable());
            }
        }

    }

    protected abstract Drawable getNetErrorDrawable();

    protected abstract String getNetErrorDes();

    protected abstract String getNetErrorAction();

    protected abstract List<MyOrderItem> filterData(List<MyOrderItem> source);

    protected abstract void fetchDataFromServer(int start, int pageSize);

    protected abstract Drawable getEmptyDrawable();

    protected abstract String getEmptyAction();

    protected abstract String getEmptyDes();

    protected int getPageIndex(int start, int pageSize) {
        int round = start / pageSize;

        return round + 1;
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.myorder_item_list,
                null);
        return new MyOderViewHolder(itemView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {
        final MyOderViewHolder holder = (MyOderViewHolder) _holder;
        final MyOrderItem item = (MyOrderItem) _item;
        holder.mRootView.setVisibility(View.VISIBLE);
        String goodspic = item.goodsPic;
        if (!TextUtils.isEmpty(goodspic)) {
            String[] split = goodspic.split(",");
            if (split.length > 0) {
                String picShow = split[0];
                Glide.with(getContext()).load(picShow).asBitmap()
                        .placeholder(R.drawable.pic_loading)
                        .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
                        .animate(R.anim.fade_in_image).into(holder.mCoverIv);
            }
        } else {
            holder.mCoverIv.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
        }

        holder.mNameTv.setText(item.goodsName);
        String format = String.format(getString(R.string.one_dollar_periods_num_1),
                item.periodsNum);
        holder.mPeriodsNumTv.setText(format);
        format = String.format(getString(R.string.one_dollar_join_count_1), item.joinNum);
        holder.mJoinNumTv.setText(format);
        setStatusView(holder.mStatusTv, item.status);

        holder.mJoinAgainTv.setVisibility(item.showJoin ? View.VISIBLE : View.GONE);
        holder.mExpressTv.setVisibility(item.showLogistics ? View.VISIBLE : View.GONE);
        holder.mShowTv.setVisibility(item.showOrderShow ? View.VISIBLE : View.GONE);
        holder.mRootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2OrderDetailPage(item.orderId);
            }
        });
        holder.mJoinAgainTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2GoodsPurchasePage(item.goodsNoNext);
            }
        });

        holder.mExpressTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2ExpressDetailPage(item.orderId, item.goodsPic);
            }
        });

        holder.mShowTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2OrderShowBuildPage(item.orderId, item.barcode, item.goodsName, item.periodsNum,
                        item.goodsPic);
            }
        });
	    holder.mAddAddressTv.setVisibility(item.showPrintAddress ? View.VISIBLE :View.GONE);
        holder.mAddAddressTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2AddressPage(item.orderId);
            }
        });
        holder.mAddAddressTv.setText((mUserAddressItems == null || mUserAddressItems.isEmpty())
                ? getString(R.string.one_dollar_user_add_address)
                : getString(R.string.one_dollar_user_select_address));
    }

    private void jump2OrderDetailPage(long orderId) {
        OrderDetailActivity.launch(getActivity(), orderId);
    }

    private void jump2OrderShowBuildPage(long orderId, long barcode, String goodsName,
                                         long periodsNum, String goodsPic) {
        OrderShowBuildActivity.launch(getActivity(), OrderShowBuildActivity.REQUEST_CODE_NORMAL,orderId, barcode, goodsName, periodsNum,
                goodsPic);
    }

    private void jump2ExpressDetailPage(long orderId, String goodsPic) {
        OrderExpressActivity.launch(getActivity(), orderId, goodsPic);
    }

    private void jump2GoodsPurchasePage(long goodsNoNext) {
        GoodsPurchaseActivity.launch(getActivity(), goodsNoNext);
    }

    private void jump2AddressPage(long orderId) {
        if (mUserAddressItems == null || mUserAddressItems.isEmpty()) {
            UserAddressBuildActivity.launch(getActivity(),
                    UserAddressBuildActivity.BUILD_TYPE_INSERT, null, true, orderId);
        } else {
            UserAddressActivity.launch(getActivity(), UserAddressActivity.REQUEST_CODE_SELECT,
                    orderId);
        }

    }

    private void setStatusView(TextView statusTv, int status) {
        statusTv.setVisibility(View.VISIBLE);
        switch (status) {
            case MyOrderItem.STATUS_NOT_WINNING:
                statusTv.setText(getString(R.string.one_dollar_order_status_not_winning));
                break;
            case MyOrderItem.STATUS_WINNED:
                statusTv.setText(getString(R.string.one_dollar_order_status_winning));
                break;
            case MyOrderItem.STATUS_ANNOUNCING:
                statusTv.setText(getString(R.string.one_dollar_order_status_announcing));
                break;
            case MyOrderItem.STATUS_QUIT:
                statusTv.setText(getString(R.string.one_dollar_order_status_quit));
                break;
            default:
                statusTv.setVisibility(View.GONE);
                break;

        }
    }


    protected void changeOrderAddress(UserAddressItem item, long orderId) {
        if (orderId <= 0 || item == null) {
            return;
        }
        Map<String, Object> params = new HashMap();
        params.put("address", item.address);
        params.put("area", item.area);
        params.put("city", item.city);
        params.put("province", item.province);
        params.put("consigneeName", item.consigneeName);
        params.put("consigneePhone", item.consigneePhone);
        params.put("orderId", orderId);
        ApiClientHelper.postApi(ApiSetting.changeOrderAddress(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {
                if (!result.success) {
                    ToastUtil.showMessage(getActivity(),
                            getString(R.string.one_dollar_user_address_insert_failed));
                }
                ToastUtil.showMessage(getActivity(),
                        getString(R.string.one_dollar_user_address_insert_suc));
	            mRecyclerView.refreshData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.showMessage(getActivity(),
                        getString(R.string.one_dollar_user_address_insert_failed));
            }
        }, this);
    }

    class MyOderViewHolder extends BaseRvAdapter.SampleViewHolder {
        @Bind(R.id.rootView)
        View mRootView;
        @Bind(R.id.iv_goods_cover)
        ImageView mCoverIv;
        @Bind(R.id.tv_goods_name)
        TextView mNameTv;
        @Bind(R.id.tv_periodsnum)
        TextView mPeriodsNumTv;
        @Bind(R.id.tv_joinnum)
        TextView mJoinNumTv;
        @Bind(R.id.tv_order_status)
        TextView mStatusTv;
        @Bind(R.id.tv_order_express)
        TextView mExpressTv;
        @Bind(R.id.tv_order_join_again)
        TextView mJoinAgainTv;
        @Bind(R.id.tv_order_show)
        TextView mShowTv;
        @Bind(R.id.tv_add_address)
        TextView mAddAddressTv;

        public MyOderViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

}
